# coding:utf-8

import os
from base import Base
from common import error


class Admin(Base):

    def __init__(self, username, user_json, gift_json):
        self.username = username
        super().__init__(user_json, gift_json)

        self.get_user()

    def get_user(self):
        users = self._Base__read_users()
        current_user = users.get(self.username)
        if current_user == None:
            raise error.NotUserError('Not user %s' % self.username)
        if current_user['active'] == False:
            raise error.UserActiveError('User active error')
        if current_user['role'] != 'admin':
            raise error.RoleError('permission')
        self.user = current_user
        self.role = current_user.get('role')
        self.name = current_user.get('username')
        self.active = current_user.get('active')

    def add_user(self, username, role):
        self.__check()
        self._Base__write_user(username=username, role=role)

    def update_user_active(self, username):
        self.__check()
        self._Base__change_active(username=username)

    def update_user_role(self, username, role):
        self.__check()
        self._Base__change_role(username=username, role=role)

    def add_gift(self, first_level, second_level, gift_name, gift_count):
        self.__check()
        self._Base__write_gifts(first_level=first_level, second_level=second_level, gift_name=gift_name,
                                gift_count=gift_count)

    def delete_gift(self, first_level, second_level, gift_name):
        self.__check()
        self._Base__delete_gift(first_level=first_level, second_level=second_level, gift_name=gift_name)

    def update_gift(self, first_level, second_level, gift_name, gift_count):
        self.__check()
        self._Base__gift_update(first_level=first_level, second_level=second_level, gift_name=gift_name,
                                gift_count=gift_count, is_admin=True)

    def __check(self, message='permission'):
        self.get_user()
        if self.role != 'admin':
            raise Exception('permission')


if __name__ == '__main__':
    user_json = os.path.join(os.getcwd(), 'storage', 'user.json')
    gift_json = os.path.join(os.getcwd(), 'storage', 'gift.json')

    admin = Admin('jack', user_json=user_json, gift_json=gift_json)
    # admin.get_user()
    # print(admin.user, admin.role, admin.name, admin.active)
    # admin.add_user('lili', 'normal')
    # admin.update_user_role('lili', 'admin')
    # admin.add_gift('level4', 'level1', 'tv', 10)
    # admin.delete_gift(first_level='level1', second_level='level1', gift_name='iphone11')
    # admin.update_gift('level1', 'level2', 'kindle', 100)
    admin.update_user_active('tom')
